package com.xuyuan.concurrent.lock;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicExample {
    private static final AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {
        System.out.println(count.addAndGet(10));
        System.out.println(count.decrementAndGet());
        System.out.println(count.incrementAndGet());
        count.set(1000);
        System.out.println(count.get());
        boolean b = count.compareAndSet(1000, 10000);
        System.out.println(b);
        System.out.println(count.get());



        // 线程1
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                count.incrementAndGet(); // 原子性的增加操作
            }
        });

        // 线程2
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                count.incrementAndGet(); // 原子性的增加操作
            }
        });

        // 启动线程
        thread1.start();
        thread2.start();

        // 等待线程结束
        try {
            thread1.join(); //主线程等待thread1执行完毕
            thread2.join(); //主线程等待thread2执行完毕
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 输出最终结果
        System.out.println("Final count value: " + count.get());
    }
}
